package main

import (
	"context"
	"go-ddd/ui/router"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"
)

type server struct {
	server *http.Server
}

func newServer(addr string, handler http.Handler) *server {
	server := new(server)
	server.server = &http.Server{
		Addr:         addr,
		Handler:      handler,
	}
	return server
}

func (s *server) start() {
	go func() {
		if err := s.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("http server err: %s\n", err)
		}
		//printServerInfo()
	}()

	s.watch()
}

// Wait for interrupt signal to gracefully shutdown the server with a timeout of 5 seconds.
func (s *server) watch() {
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit

	log.Println("shutdown server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := s.server.Shutdown(ctx); err != nil {
		log.Fatal("server shutdown Err:", err)
	}
}

func main() {
	engine := router.NewEngine()
	server := newServer(":8080", engine)
	server.start()
}
